package com.chart.chart.manager;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chart.chart.domian.ChartStatistics;
import com.chart.chart.domian.req.PUReq;
import com.chart.chart.domian.req.UListReq;
import com.chart.chart.domian.req.UVipsReq;
import com.chart.chart.domian.resp.PageResp;
import com.chart.chart.domian.resp.UserResp;
import com.chart.chart.domian.vo.PUVo;
import com.chart.chart.domian.vo.StatisticsVo;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.system.domain.RegistrationChannels;
import com.chart.system.domain.SysUserOrder;
import com.chart.system.domain.vo.SysUserVo;
import com.chart.system.mapper.SysUserMapper;
import com.chart.system.mapper.SysUserOrderMapper;
import com.chart.system.service.ISysUserOrderService;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.RegistrationChannelsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.chart.common.utils.PageUtils.startPage;

@Component
public class UserStatisticsManager {

    @Resource
    private SysUserMapper userMapper;
    @Resource
    private ISysUserService userService;
    @Resource
    private SysUserOrderMapper userOrderMapper;
    @Resource
    private ISysUserOrderService userOrderService;

    @Autowired
    RegistrationChannelsService registrationChannelsService;
    @Resource
    private UserStatisticsManager userManager;

    public List<UserResp> getListBy(UListReq req) {


        List<UserResp> resp = userMapper.getListBy(req);

        return resp;
    }


//    public PageResp<UserResp> getListBys(UListReq req) {
//        long totalCount = userMapper.countTotalUsers(req);
//        List<UserResp> list = userMapper.getListBys(req);
//
//        for (UserResp userResp : list) {
//            // 处理 hasPaid
//            if (userResp.getHasPaid() != null) {
//                userResp.setHasPaidInfo(userResp.getHasPaid() == 1 ? "是" : "否");
//            }
//
//            // 处理 sex
//            if ("3".equals(userResp.getSex())) {
//                userResp.setSex("null");
//            }
//
//            // 处理 hasComplete
//            if (userResp.getHasComplete() != null) {
//                switch (userResp.getHasComplete()) {
//                    case 0:
//                        userResp.setHasCompleteInfo("未完善");
//                        break;
//                    case 1:
//                        userResp.setHasCompleteInfo("已完善");
//                        break;
//                }
//            }
//
//            // 处理 platform
//            if (userResp.getPlatform() != null) {
//                switch (userResp.getPlatform()) {
//                    case 0:
//                        userResp.setPlatformSecond("手机注册");
//                        break;
//                    case 1:
//                        userResp.setPlatformSecond("电脑注册");
//                        break;
//                    default:
//                        userResp.setPlatformSecond("未知平台");
//                        break;
//                }
//            }
//
//            // 处理 knowChannel
//            String knowChannelStr = userResp.getKnowChannel();
//            if (knowChannelStr != null) {
//                try {
//                    long knowChannel = Long.parseLong(knowChannelStr);
//                    if (knowChannel == 8) {
//                        String otherKnowChannel = userResp.getOtherKnowChannel();
//                        if (otherKnowChannel != null) {
//                            userResp.setKnowChannelSecond(otherKnowChannel);
//                        }
//                    } else {
//                        LambdaQueryWrapper<RegistrationChannels> lqw = new LambdaQueryWrapper<>();
//                        lqw.eq(RegistrationChannels::getId, knowChannel);
//                        RegistrationChannels one = registrationChannelsService.getOne(lqw);
//                        if (one != null) {
//                            userResp.setKnowChannelSecond(one.getName());
//                        }
//                    }
//                } catch (NumberFormatException e) {
//                   // logger.error("解析 knowChannel 失败: " + knowChannelStr, e);
//                }
//            }
//        }
//
//
//      Integer  registerTotal =  userService.selectCount();
//        // 初始化 PageResp
//        PageResp<UserResp> pageResp = new PageResp<>();
//        pageResp.setList(list);
//        pageResp.setTotal(totalCount);
//        pageResp.setTotalUser(list.size());
//        pageResp.setRegisterTotal(registerTotal);
//        return pageResp;
//    }





    public AjaxResult getSource() {
        return AjaxResult.success(userMapper.getregChannel(null));
    }


    /**
     * @param req
     * @return
     */
    public List<PUVo> getPU(PUReq req) {
        Integer eventType = req.getEventType();
        if (eventType == 0) {
            return userMapper.getSaveOrImport(req);
        } else {
            List<PUVo> forward = userMapper.getForward(req);
            forward.get(0).setName("转发点击");
            return forward;
        }
    }

/*    @Transactional
    public AjaxResult editVips(UVipsReq req) {
        List<Long> ids = req.getUserIds();
        if (ids.isEmpty()) {
            return AjaxResult.error("请勾选用户");
        }
        List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId, ids));
        List<SysUserOrder> userOrderList = userOrderMapper.selectList(Wrappers.<SysUserOrder>lambdaQuery().in(SysUserOrder::getUserId, ids));

        boolean result = req.getExpirationTime().isBefore(LocalDateTimeUtil.now());
        if (result) {
            //取消vip
            userList.forEach(u -> u.setIsVip(0));
        } else {
            //添加
            userList.forEach(u -> u.setIsVip(1));
        }
        userService.updateBatchById(userList);

        List<SysUserOrder> newOrderList = userList.stream()
                .map(user -> findOrder(user, userOrderList, req.getExpirationTime()))
                .collect(Collectors.toList());

        userOrderService.updateBatchById(newOrderList);
        return AjaxResult.success();
    }*/
@Transactional
public AjaxResult editVips(UVipsReq req) {
    List<Long> ids = req.getUserIds();
    if (ids.isEmpty()) {
        return AjaxResult.error("请勾选用户");
    }
    List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId, ids));
    List<SysUserOrder> userOrderList = userOrderMapper.selectList(Wrappers.<SysUserOrder>lambdaQuery().in(SysUserOrder::getUserId, ids));

    boolean result = req.getExpirationTime().isBefore(LocalDateTimeUtil.now());
    if (result) {
        //取消vip
        userList.forEach(u -> u.setIsVip(0));
    } else {
        //添加
        userList.forEach(u -> u.setIsVip(1));
    }
    userService.updateBatchById(userList);

    List<SysUserOrder> newOrderList = userList.stream()
            .map(user -> findOrder(user, userOrderList, req.getExpirationTime()))
            .collect(Collectors.toList());
    userOrderService.saveOrUpdateBatch(newOrderList);
    return AjaxResult.success();
}
    /**
     * 匹配用户会员订单
     *
     * @param user
     * @param userOrderList
     * @param expirationTime
     * @return
     */
    private SysUserOrder findOrder(SysUser user, List<SysUserOrder> userOrderList, LocalDateTime expirationTime) {
        SysUserOrder userOrder = userOrderList.stream()
                .filter(order -> order.getUserId().equals(user.getUserId()))
                .findFirst()
                .orElse(new SysUserOrder());
        userOrder.setExpirationTime(expirationTime);
        userOrder.setUserId(user.getUserId());
        userOrder.setRemark("系统修改");
        return userOrder;
    }

    @Transactional
    public AjaxResult updateVips() {
        LocalDateTime now = LocalDateTimeUtil.now();
        List<SysUser> vipList = userMapper.selectList(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getIsVip, 1));
        if (!vipList.isEmpty()) {
            List<Long> idList = vipList.stream().map(SysUser::getUserId).collect(Collectors.toList());
            List<SysUserOrder> userOrderList = userOrderMapper.selectList(Wrappers.<SysUserOrder>lambdaQuery().in(SysUserOrder::getUserId, idList));
            List<Long> expiredIds = new ArrayList<>();
            userOrderList.forEach(o -> {
                if (o.getExpirationTime().isAfter(now)) {
                    expiredIds.add(o.getUserId());
                }
            });
            List<SysUser> expired = getExpiredUser(expiredIds, vipList);
            userService.updateBatchById(expired);
        }
        //checkVips();
        return AjaxResult.success();
    }


    /**
     * 确认vip用户
     */
    private void checkVips() {
        LocalDateTime now = LocalDateTimeUtil.now();
        List<SysUserOrder> userOrderList = userOrderMapper.selectList(null);
        List<SysUserOrder> vipList = new ArrayList<>();
        userOrderList.forEach(u -> {
            if (u.getExpirationTime().isAfter(now)) {
                vipList.add(u);
            }
        });
        List<Long> vips = vipList.stream().map(SysUserOrder::getUserId).collect(Collectors.toList());
        List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId, vips));
        List<SysUser> vipUserList = new ArrayList<>();
        userList.forEach(e -> {
            e.setIsVip(1);
            vipUserList.add(e);
        });
        userService.updateBatchById(vipUserList);
    }

    /**
     * 获取会员过期用户
     *
     * @param expiredIds
     * @param vipList
     * @return
     */
    private List<SysUser> getExpiredUser(List<Long> expiredIds, List<SysUser> vipList) {
        List<SysUser> expiredList = new ArrayList<>();
        expiredIds.forEach(e -> {
            SysUser user = vipList.stream().filter(v -> v.getUserId().equals(e)).findFirst().orElse(new SysUser());
            user.setIsVip(0);
            expiredList.add(user);
        });
        return expiredList;
    }



}
